

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blogshow/img/favicon.png">
  <link rel="icon" href="/blogshow/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  <meta name="description" content="Java NIO一、简介Java NIO（New IO）是从Java1.4版本开始引入的一个新的IO API，可以替代标准的Java IO API。NIO与原理啊的IO有同样的作用和目的，但是使用的方式完全不同，NIO支持面向缓冲区的，基于通道的IO操作。NIO将以更加高效的方式进行文件的读写和操作 二、IO与NIO的区别   IO NIO    面向流(Stream Oriented) 面向缓冲">
<meta property="og:type" content="article">
<meta property="og:title" content="Java NIO">
<meta property="og:url" content="https://gitee.com/jiwentao/blogshow/2020/10/22/nio/index.html">
<meta property="og:site_name" content="啊泽show的博客">
<meta property="og:description" content="Java NIO一、简介Java NIO（New IO）是从Java1.4版本开始引入的一个新的IO API，可以替代标准的Java IO API。NIO与原理啊的IO有同样的作用和目的，但是使用的方式完全不同，NIO支持面向缓冲区的，基于通道的IO操作。NIO将以更加高效的方式进行文件的读写和操作 二、IO与NIO的区别   IO NIO    面向流(Stream Oriented) 面向缓冲">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/blogshow/.com//netty/%E4%BC%A0%E7%BB%9FIO.png">
<meta property="og:image" content="https://gitee.com/blogshow/.com//netty/NIO.png">
<meta property="og:image" content="https://gitee.com/blogshow/.com//netty/buffer%E7%BB%A7%E6%89%BF%E5%85%B3%E7%B3%BB.png">
<meta property="article:published_time" content="2020-10-22T02:00:00.000Z">
<meta property="article:modified_time" content="2021-10-22T02:05:01.314Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://gitee.com/blogshow/.com//netty/%E4%BC%A0%E7%BB%9FIO.png">
  
  <title>Java NIO - 啊泽show的博客</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="/blogshow/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/blogshow/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"gitee.com","root":"/blogshow/","version":"1.8.12","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname"}},"search_path":"/blogshow/local-search.xml"};
  </script>
  <script  src="/blogshow/js/utils.js" ></script>
  <script  src="/blogshow/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/blogshow/">
      <strong>啊泽show</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blogshow/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blogshow/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blogshow/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blogshow/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blogshow/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blogshow/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" target="_self" href="javascript:;" role="button"
                 data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="iconfont icon-books"></i>
                文档
              </a>
              <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/">
                    
                    主题博客
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/docs/guide/">
                    
                    配置指南
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/docs/icon/">
                    
                    图标用法
                  </a>
                
              </div>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/blogshow/img/index_banner.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="Java NIO">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2020-10-22 10:00" pubdate>
        2020年10月22日 上午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.4k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      4 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Java NIO</h1>
            
            <div class="markdown-body">
              <h1 id="Java-NIO"><a href="#Java-NIO" class="headerlink" title="Java NIO"></a>Java NIO</h1><h2 id="一、简介"><a href="#一、简介" class="headerlink" title="一、简介"></a>一、简介</h2><p>Java NIO（New IO）是从Java1.4版本开始引入的一个新的IO API，可以替代标准的Java IO API。NIO与原理啊的IO有同样的作用和目的，但是使用的方式完全不同，NIO支持面向缓冲区的，基于通道的IO操作。NIO将以更加高效的方式进行文件的读写和操作</p>
<h2 id="二、IO与NIO的区别"><a href="#二、IO与NIO的区别" class="headerlink" title="二、IO与NIO的区别"></a>二、IO与NIO的区别</h2><table>
<thead>
<tr>
<th>IO</th>
<th>NIO</th>
</tr>
</thead>
<tbody><tr>
<td>面向流(Stream Oriented)</td>
<td>面向缓冲区(Buffer Oriented)</td>
</tr>
<tr>
<td>阻塞IO(Blocking IO)</td>
<td>非阻塞IO(NonBlocking IO)</td>
</tr>
<tr>
<td></td>
<td>选择器(Selectors)</td>
</tr>
</tbody></table>
<h3 id="1、面向流和缓冲区"><a href="#1、面向流和缓冲区" class="headerlink" title="1、面向流和缓冲区"></a>1、面向流和缓冲区</h3><p><strong>IO</strong><br>传统IO在传输数据时，根据输入输出的不同需要分别建立不同的链接，而且传输的数据是以流的形式在链接上进行传输的</p>
<p>就像自来水要通过水管将自来水厂和家连接起来一样</p>
<p><img src="/blogshow/.com//netty/%E4%BC%A0%E7%BB%9FIO.png" srcset="/blogshow/img/loading.gif" lazyload alt="传统IO"></p>
<p><strong>NIO</strong><br>NIO在传输数据时，会在输入输出端之间建立通道，然后将数据放入到缓冲区中。缓冲区通过通道来传输数据</p>
<p>这里通道就像是铁路，能够连通两个地点。缓冲区就像是火车，能够真正地进行数据的传输<br><img src="/blogshow/.com//netty/NIO.png" srcset="/blogshow/img/loading.gif" lazyload alt="NIO"></p>
<h2 id="三、通道与缓冲区"><a href="#三、通道与缓冲区" class="headerlink" title="三、通道与缓冲区"></a>三、通道与缓冲区</h2><p>Java NIO系统的核心在于：通道(Channel)和缓冲区(Buffer)。通道表示打开到 IO 设备(例如：文件、套接字)的连接。若需要使用 NIO 系统，需要获取用于连接 IO 设备的通道以及用于容纳数据的缓冲区。然后操作缓冲区，对数据进行处理</p>
<p>简而言之，通道负责传输，缓冲区负责存储</p>
<h2 id="四、缓冲区-Buffer"><a href="#四、缓冲区-Buffer" class="headerlink" title="四、缓冲区(Buffer)"></a>四、缓冲区(Buffer)</h2><h3 id="1、缓冲区类型"><a href="#1、缓冲区类型" class="headerlink" title="1、缓冲区类型"></a>1、缓冲区类型</h3><p>Buffer 就像一个数组，可以保存多个相同类型的数据。根据数据类型不同(boolean 除外) ，有以下Buffer 常用子类</p>
<ul>
<li>ByteBuffer</li>
<li>CharBuffer</li>
<li>ShortBuffer</li>
<li>IntBuffer</li>
<li>LongBuffer</li>
<li>FloatBuffer</li>
<li>DoubleBuffer</li>
</ul>
<p><strong>各种类型的缓冲区中，都有一个对应类型的数组，</strong>如<br>ByteBuffer</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java">finanl <span class="hljs-keyword">byte</span>[] hb;<br></code></pre></td></tr></table></figure>
<p>IntBuffer</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java">finanl <span class="hljs-keyword">int</span>[] hb;<br></code></pre></td></tr></table></figure>
<p><strong>他们的继承关系如下</strong><br><img src="/blogshow/.com//netty/buffer%E7%BB%A7%E6%89%BF%E5%85%B3%E7%B3%BB.png" srcset="/blogshow/img/loading.gif" lazyload alt="继承关系"></p>
<h3 id="2、获取缓冲区"><a href="#2、获取缓冲区" class="headerlink" title="2、获取缓冲区"></a>2、获取缓冲区</h3><p>通过<strong>allocate方法</strong>可以获取一个对应缓冲区的对象，它是缓冲区类的一个静态方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 获取一个容量大小为1024字节的字节缓冲区</span><br>ByteBuffer byteBuffer = ByteBuffer.allocate(<span class="hljs-number">1024</span>);<br></code></pre></td></tr></table></figure>
<h3 id="3、核心属性"><a href="#3、核心属性" class="headerlink" title="3、核心属性"></a>3、核心属性</h3><p>缓冲区的父类Buffer中有几个核心属性，如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// Invariants: mark &lt;= position &lt;= limit &lt;= capacity</span><br><span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> mark = -<span class="hljs-number">1</span>;<br><span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> position = <span class="hljs-number">0</span>;<br><span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> limit;<br><span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> capacity;<br></code></pre></td></tr></table></figure>
<ul>
<li>capacity：缓冲区的容量。通过构造函数赋予，一旦设置，无法更改</li>
<li>limit：缓冲区的界限。位于limit 后的数据不可读写。缓冲区的限制不能为负，并且<strong>不能大于其容量</strong></li>
<li>position：下一个读写位置的索引（类似PC）。缓冲区的位置不能为负，并且不能大于limit</li>
<li>mark：记录当前position的值。position被改变后，可以通过调用reset() 方法恢复到mark的位置。</li>
</ul>
<p>以上四个属性必须满足以下要求<br><strong>mark &lt;= position &lt;= limit &lt;= capacity</strong></p>
<h3 id="4、核心方法"><a href="#4、核心方法" class="headerlink" title="4、核心方法"></a>4、核心方法</h3><p><strong>put()方法</strong></p>
<ul>
<li>put()方法可以将一个数据放入到缓冲区中。</li>
<li>进行该操作后，postition的值会+1，指向下一个可以放入的位置。capacity = limit ，为缓冲区容量的值。</li>
</ul>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/blogshow/categories/netty/">netty</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/blogshow/tags/java/">java</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/blogshow/2020/10/25/Netty%E5%AD%A6%E4%B9%A0%E4%B9%8BNIO%E5%9F%BA%E7%A1%80/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Netty学习之NIO基础</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/blogshow/2020/10/21/%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/">
                        <span class="hidden-mobile">搭建一个属于你自己的博客</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/blogshow/js/events.js" ></script>
<script  src="/blogshow/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/blogshow/js/local-search.js" ></script>



  
    <script  src="/blogshow/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/blogshow/js/boot.js" ></script>


</body>
</html>
